#include "httpSever.hpp"
#include "Utils.hpp"
#include "Daemonization.hpp"
#include <memory>
#include<errno.h>
#include <string.h>
#include <vector>
#include <fstream>
#define ROOT "./wwwroot"
void httpSevice(int sock)
{
    char buffer[10240];
    size_t s = recv(sock,buffer,sizeof(buffer) - 1,0);
    if(s < 0)
    {
        logMessage(ERROR,"recv error %d %s\n",errno,strerror(errno));
    }
    else if(s == 0)
    {
        logMessage(NORMAL,"客户端关闭\n");
    }
    else
    {
        buffer[s] = 0;
        //cout<<buffer<<endl;
    }
    
    //拿到请求了
    //string requst = buffer;
    vector<string> vec;
    Utils::CutRequset(buffer,vec);
    string Get_First_Line = vec[0];
    vector<string> vblock;
    string Get_Root;
    Utils::CutRequset(vec[0],vblock," ",1);
    string target = vblock[1];
    if(target == "/") target = "/index.html";
    target = ROOT + target;
    ifstream in(target);
    string content;
    if(in.is_open())
    {
        string line;
        while(getline(in,line))
        {
            content += line;
        }
        in.close();
    }
    string Response;
    if(content.empty()) Response += "HTTP/1.1 404 NotFound\r\n";
    else Response += "HTTP/1.1 200 OK\r\n";
    Response += "\r\n";
    Response += content;
    send(sock,Response.c_str(),Response.size(),0);
}

int main(int argc,char* argv[])
{
    if(argc != 2)
    {
        logMessage(ERROR,"请输入两个参数,待执行程序 端口号\n");
        exit(1);
    }
    Daemonization();
    uint16_t port = atoi(argv[1]);
    unique_ptr<httpSever> hs(new httpSever(port,httpSevice));
    hs->start();
    return 0;
}